<?php

class RenbaoController extends Controller {

    //承保
    public function actionInsure() {
        // 接收投保报文
        $data = trim(file_get_contents("php://input"));
        if(!$data){
            echo '{"waterNo":"","retCode":"11","retDesc":"无参数","policyNum":"","transTime":""}';die;
        }
        // 日志记录
        $this->log("同程投保申请火综报文格式：".$data);
        $data = json_decode($data, true);
        if(!$data){
            echo '{"waterNo":"","retCode":"11","retDesc":"参数不是json格式","policyNum":"","transTime":""}';die;
        }
        if(!$data['cooperation']){
            echo '{"waterNo":"","retCode":"11","retDesc":"缺少参数:cooperation","policyNum":"","transTime":""}';die;
        }
        //提供给第三方的产品代码
        $third_party_code = $data['rationType'];
        $model = CsConfig::model()->findByAttributes(array('third_party_code'=>$third_party_code));
        if (!$model) {
            echo '{"waterNo":"","retCode":"11","retDesc":"产品不存在","policyNum":"","transTime":""}';die;
        }
        //校验参数
        $falsemsg=array(
            'waterNo' => $data['waterNo'],
            'retCode' => '11',
            'retDesc'=>'',
            'policyNum'=>'',
            'transTime'=>'',
        );

        $get = array(
            'waterNo'=>$data['waterNo'],
            'startDate'=>$data['startDate'],
            'rationType'=>$data['rationType'],
            'insuredName'=>$data['insuredList'][0]['insuredName'],
            'insuredIdentifyType'=>$data['insuredList'][0]['insuredIdentifyType'],
            'insuredIdentifyNumber'=>$data['insuredList'][0]['insuredIdentifyNumber'],
            'policyName'=>$data['policyName'],
            'policyIdentifyType'=>$data['policyIdentifyType'],
            'policyIdentifyNumber'=>$data['policyIdentifyNumber'],
        );
        //非空判断
        foreach ($get as $key => $value) {
            if($value == ''){
                $falsemsg['retDesc']="缺少参数:".$key;
                die($this->JSON($falsemsg));
            }
        }
        if($data['policyIdentifyType']!='01'){//投保人身份证
            if(!$data['policyBirthday']){
                $falsemsg['retDesc']="缺少参数:policyBirthday";
                die($this->JSON($falsemsg));
            }
            if(!$data['policySex']){//投保人性别
                $falsemsg['retDesc']="缺少参数:policySex";
                die($this->JSON($falsemsg));
            }
            //格式判断
        }elseif(!$this->idcard($data['policyIdentifyNumber'])){
            $falsemsg['retDesc']="参数policyIdentifyNumber格式不正确";
            die($this->JSON($falsemsg));
        }
        if ($data['policyBirthday'] && !strtotime($data['policyBirthday'])) {
            $falsemsg['retDesc']="参数policyBirthday格式不正确";
            die($this->JSON($falsemsg));
        }
        if(!preg_match('/^\d*$/',$data['rationType'])) {
            $falsemsg['retDesc'] = "参数rationType格式不正确";
            die($this->JSON($falsemsg));
        }
        if(!in_array($data['policyIdentifyType'],array('01','02','03','09','11'))){
            $falsemsg['retDesc']="参数policyIdentifyType格式不正确";
            die($this->JSON($falsemsg));
        }
        if(!in_array($data['policySex'],array('01','02',''))){
            $falsemsg['retDesc']="参数policySex格式不正确";
            die($this->JSON($falsemsg));
        }
        //被保人列表信息
        $InsuedInfo = $data['insuredList'];
        foreach ($InsuedInfo as $key => $value) {
            $k = $key+1;
            if($value['insuredIdentifyType']!='01'){
                if(!$value['insuredBirthday']){
                    die('{"waterNo":"'.$data['waterNo'].'","retCode":"11","retDesc":"缺少参数:第'.$k.'被保险人insuredBirthday","policyNum":"","transTime":""}');
                }
                if(!$value['insuredSex']){
                    die('{"waterNo":"'.$data['waterNo'].'","retCode":"11","retDesc":"缺少参数:第'.$k.'被保险人insuredSex","policyNum":"","transTime":""}');
                }
            }elseif (!$this->idcard($value['insuredIdentifyNumber'])) {
                $falsemsg['retDesc']="第".$k."被保险人参数insuredIdentifyNumber格式不正确";
                die($this->JSON($falsemsg));
            }
            if ($value['insuredBirthday'] && !strtotime($value['insuredBirthday'])) {
                $falsemsg['retDesc']="第".$k."被保险人参数insuredBirthday格式不正确";
                die($this->JSON($falsemsg));
            }
            if (!in_array($value['insuredSex'],array('01','02',''))) {
                $falsemsg['retDesc']="第".$k."被保险人参数insuredSex格式不正确";
                die($this->JSON($falsemsg));
            }
            if(!in_array($value['insuredPolRelation'],array('01','10','40','50','13','99',''))){
                $falsemsg['retDesc']="第".$k."被保险人参数insuredPolRelation格式不正确";
                die($this->JSON($falsemsg));
            }
        }

        //判断是否重复提交
        $dist = RenXcImportinfo::model()->findByAttributes(array(
            'cWaterNo'=>$data['waterNo'],
            'cooperation'=>$data['cooperation']
        ));
        if($dist) {
            //如果重复  则返回已投保信息
            $return = array();
            $return['waterNo'] = $dist->cWaterNo;
            $return['retCode'] = $dist->retCode;
            $return['retDesc'] = $dist->retDesc;
            $return['policyNum'] = $dist->policyNum;
            $return['transTime'] = date('Y-m-d H:i:s',$dist->realDate);
            $return['epolicyAddress'] = $dist->epolicyAddress;
            echo $this->JSON($return);
        } else {
            //投保人
            $holder = new CsPolicyholders();
            $holder->ApplicantName = $data['policyName'];
            $holder->ApplicantZJNum = $data['policyIdentifyNumber'];
            $holder->ApplicantZJType = $data['policyIdentifyType'];
            $holder->ApplicantMobile = $data['policyMobile']?$data['policyMobile']:'';
            $holder->ApplicantType = '1';
            if($data['policyBirthday']){
                $holder->birthday = date('Y-m-d',strtotime($data['policyBirthday']));
            }else{
                $holder->birthday = $this->birthIDCard($data['policyIdentifyNumber']);
            }
            if($data['policySex']){
                $holder->sex = $data['policySex'];
            }else{
                $holder->sex = $this->sexIDCard($data['policyIdentifyNumber']);
            }
            $holder->ApplicantEmail = $data['policyEmail'];
            $holder->create_time = time();
            $holder->save(false);

            //存入出保交易流水表   后续投保使用
            $approval = new RenApprovaltrans();
            $approval->TransID = $data['waterNo'];
            $approval->MerchantNo = $data['cooperation'];
            $approval->TransDate = date('Ymd',time());
            $approval->TransTime = date('His',time());
            $approval->EffectDate = date('Ymd',strtotime($data['startDate']));
            $approval->EffectDate = date('His',strtotime($data['startDate']));
            $approval->proposer_id = $holder->id;
            $approval->ProductCode = $data['rationType'];
            $approval->rationType = $model->rationType;
            $approval->riskCode = $model->riskCode;
            $approval->premium = $data['premium'];
            $approval->startDate = date('Y-m-d H:i:s',strtotime($data['startDate']));
            $approval->waterNo = $data['waterNo'];
            $approval->OrderID = $data['orderNo'];
            $approval->trip = $data['trip'];
            $approval->date = $data['date'];
            if($data['endDate']){
                $approval->endDate = date('Y-m-d H:i:s',strtotime($data['endDate']));
            }else{
                $approval->endDate = date('Y-m-d H:i:s',strtotime($data['startDate'])+60*60*24*7);
            }
            $approval->inputDate = date('Y-m-d H:i:s',time());
            $approval->holderNum = count($InsuedInfo);
            $approval->issuedDate = date('Y-m-d H:i:s',time());
            $approval->DepartureCity = $data['departureCity'];
            $approval->ArrivalCity = $data['arrivalCity'];
            $approval->CarNo = $data['carNo'];
            $approval->CarNum = $data['carNum'];
            $approval->address = $data['address'];
            $approval->school = $data['school'];
            $approval->class = $data['class'];
            $approval->createTime = time();
            $approval->save(false);

            //被保人
            foreach ($InsuedInfo as $value) {
                $Insued = new RenInsuredinfo();
                $Insued->approvaltrans_id = $approval->id;
                $Insued->InsuedName = $value['insuredName'];
                $Insued->InsuedZJNo = $value['insuredIdentifyNumber'];
                $Insued->InsuedZJType = $value['insuredIdentifyType'];
                $Insued->InsuedMobile = $value['insuredMobile']?$value['insuredMobile']:'';
                $idcard = $value['insuredIdentifyNumber'];
                if($value['insuredBirthday']){
                    $Insued->birthday = date('Y-m-d',strtotime($value['insuredBirthday']));
                }else{
                    $Insued->birthday = $this->birthIDCard($idcard);
                }
                if($value['insuredSex']){
                    $Insued->sex = $value['insuredSex'];
                }else{
                    $Insued->sex = $this->sexIDCard($idcard);
                }
                $Insued->insRelationApp = $value['insuredPolRelation']?$value['insuredPolRelation']:'99';
                $Insued->create_time = time();
                $Insued->save(false);
            }

            //根据产品动态分配
            $thirdPartyCode = $model->third_party_code;  //提供给第三方的产品编号
            $productObj = $this->getTargetCompany($thirdPartyCode);
            if($productObj->in_company == "RB") { //人保
                $this->RB($approval->id,$data,$productObj);
            }
            if($productObj->in_company == "TA") { //天安
                $this->TA($approval->id,$data,$productObj);
            }
        }
    }

    //退保
    public function actionSurrender() {
        // 接收投保报文
        $data = trim(file_get_contents("php://input"));
        //逻辑
        if(!$data){
            echo '{"waterNo":"","policyNo":"","retCode":"11","returnMsg":"无参数"}';die;
        }
        $this->log("同程退保申请报文：".$data);
        $data = json_decode($data, true);
        if(!$data){
            echo '{"waterNo":"","policyNo":"","retCode":"11","returnMsg":"参数不是json格式"}';die;
        }
        $get = array(
            'waterNo'=>$data['waterNo'],
            'cooperation'=>$data['cooperation'],
            'policyNo'=>$data['policyNo'],
            'productCode'=>$data['productCode'],
        );
        //非空判断
        foreach ($get as $key => $value) {
            if($value == ''){
                echo '{"waterNo":"","policyNo":"","retCode":"11","returnMsg":"缺少参数:'.$key.'"}';die;
            }
        }
        //保单验证
        $importinfo = RenXcImportinfo::model()->findByAttributes(array('policyNum'=>$data['policyNo']));
        if(!$importinfo){
            echo '{"waterNo":"","policyNo":"","retCode":"11","returnMsg":"该保单号不存在"}';die;
        }
        $approvaltran = RenApprovaltrans::model()->findByAttributes(array('id'=>$importinfo->approvaltrans_id));

        //判断是否重复提交
        $dist = RenSurrenderinfo::model()->findByAttributes(array(
            'policyNo' => $data['policyNo'],
            'cooperation' => $data['cooperation']
        ));
        if($dist){
            $return['waterNo'] = $dist->waterNo;
            $return['policyNo'] = $dist->policyNo;
            $return['retCode'] = $dist->retCode;
            $return['returnMsg'] = $dist->returnMsg;
            $return['transTime'] = date('Y-m-d H:i:s',$dist->realDate);
            echo $this->JSON($return);
        }else{
            $surrender = New RenSurrender;
            $surrender->waterNo = $data['waterNo'];
            $surrender->policyNo = $data['policyNo'];
            $surrender->productCode = $approvaltran->ProductCode;
            $surrender->rationType = $approvaltran->rationType;
            $surrender->startDate = $approvaltran->startDate;
            $surrender->endDate = $approvaltran->endDate;
            $surrender->premium = $approvaltran->premium;
            $surrender->cancelReason = $data['cancelReason'];
            $surrender->cooperation = $data['cooperation'];
            $surrender->createTime = time();
            $surrender->save(false);
            if ($importinfo) {
                $productObj = CsConfig::model()->findByAttributes(array('third_party_code'=>$approvaltran->ProductCode,"in_company"=>$importinfo->in_company));
                switch ($importinfo->in_company) {
                    case "TA":
                        $this->sTA($surrender->id,$data,$productObj);
                        break;
                    case "RB":
                        $this->sRB($surrender->id,$data,$productObj);
                        break;
                }
            }
        }
    }

    public function sTA($id,$data,$productObj){
        $surrender = RenSurrender::model()->findByPk($id);
        $nonce = strtoupper(md5(uniqid(mt_rand(), true)));
        $time=time();
        $arr = array(
                "requestHead" => array(
                "cooperation" => "tongcheng",
                "nonce" => $nonce,
                "sign" => $this->getSign($nonce, $time),
                "timestamp" => $time,
                "tradeNo" => $time.rand(10000, 99999),
                "tradeDate" => date("Y-m-d H:i:s"),
            ),
            "waterNo" => $data['waterNo'],
            "policyNo" => $data['policyNo'],
            "productCode" => $productObj->rationType,
            "rationType" => $productObj->riskCode
        );
        $req_str = json_encode($arr);
        $encoding = mb_detect_encoding($req_str, array('ASCII','GB2312', 'GBK','UTF-8'));
        $req_str = iconv($encoding,"GB2312",$req_str);
        $url =  Yii::app()->params['Tianan_Huo_tuibao'];
        $startime=microtime(true);
        $ret = $this->request_by_curl($url,$req_str);
        $endtime=microtime(true);
        $alltime=$endtime-$startime;
        $this->log("天安退保申请报文：".$arr);
        $this->log("天安退保返回报文：".$ret);
        $this->log("天安退保返回时间(秒)：".$alltime);
        $result = json_decode($ret,true);
        $return = array(
            'waterNo' => $data['waterNo'],
        );
        if(!$result){
            $return['retCode'] = '11';
            $return['returnMsg'] = '核心接口连接失败，请联系管理员';
        }elseif (!$result['policyNo']) {
            $return['retCode'] = '11';
            $return['returnMsg'] = '核心接口返回异常，请联系管理员';
        }else{
            $surrenderinfo = New RenSurrenderinfo;
            $surrenderinfo->surrender_id = $surrender->id;
            $surrenderinfo->cooperation = $data['cooperation'];
            $surrenderinfo->waterNo = $data['waterNo'];
            $surrenderinfo->policyNo = $result['policyNo'];
            $surrenderinfo->realDate = strtotime($result['transTime'])?strtotime($result['transTime']):time();
            $surrenderinfo->policyStatus = $result['policyStatus'];
            $surrenderinfo->retCode = $result['retCode'];
            $surrenderinfo->returnMsg = $result['returnMsg'];
            $surrenderinfo->createTime = time();
            $surrenderinfo->in_company = $productObj->in_company;
            $surrenderinfo->save(false);
            $return['policyNo'] = $result['policyNo'];
            $return['retCode'] = $result['retCode'];
            $return['returnMsg'] = $result['returnMsg'];
            $return['transTime'] = $result['transTime']?$result['transTime']:time();
        }
        echo $return_msg = $this->JSON($return);
        $this->log("同程退保返回报文：".$return_msg);
    }

    public function sRB($id,$data,$productObj){
        $surrender = RenSurrender::model()->findByPk($id);
        $arr = array(
            "waterNo" => $data['waterNo'],
            "policyNo" => $data['policyNo'],
            "productCode" => $productObj->rationType,
            "rationType" => $productObj->riskCode
        );
        $req_str = json_encode($arr);
        $encoding = mb_detect_encoding($req_str, array('ASCII','GB2312', 'GBK','UTF-8'));
        $req_str = iconv($encoding,"GB2312",$req_str);
        $url =  Yii::app()->params['Renbao_tuibao'];
        $startime=microtime(true);
        $ret = $this->request_by_curl($url,$req_str);
        $endtime=microtime(true);
        $alltime=$endtime-$startime;
        $this->log("人保退保申请报文：".$arr);
        $this->log("人保退保返回报文：".$ret);
        $this->log("人保退保返回时间(秒)：".$alltime);
        $result = json_decode($ret,true);
        $return = array(
            'waterNo' => $data['waterNo'],
        );
        if(!$result){
            $return['retCode'] = '11';
            $return['returnMsg'] = '核心接口连接失败，请联系管理员';
        }elseif (!$result['policyNo']) {
            $return['retCode'] = '11';
            $return['returnMsg'] = '核心接口返回异常，请联系管理员';
        }else{
            $surrenderinfo = New RenSurrenderinfo;
            $surrenderinfo->surrender_id = $surrender->id;
            $surrenderinfo->cooperation = $data['cooperation'];
            $surrenderinfo->waterNo = $data['waterNo'];
            $surrenderinfo->policyNo = $result['policyNo'];
            $surrenderinfo->realDate = strtotime($result['transTime'])?strtotime($result['transTime']):time();
            $surrenderinfo->policyStatus = $result['policyStatus'];
            $surrenderinfo->retCode = $result['retCode'];
            $surrenderinfo->returnMsg = $result['returnMsg'];
            $surrenderinfo->createTime = time();
            $surrenderinfo->in_company = $productObj->in_company;
            $surrenderinfo->save(false);
            $return['policyNo'] = $result['policyNo'];
            $return['retCode'] = $result['retCode'];
            $return['returnMsg'] = $result['returnMsg'];
            $return['transTime'] = $result['transTime']?$result['transTime']:time();
        }
        echo $return_msg = $this->JSON($return);
        $this->log("同程退保返回报文：".$return_msg);
    }

    /*
    * 投保天安
    */
    public function TA($id,$data,$productObj) {
        $uri =  Yii::app()->params['Tianan_Huo_toubao'];
        $req_str = $this->commonXml($id,$data,$productObj);
        $startime=microtime(true);
        $encoding = mb_detect_encoding($req_str, array('ASCII','GB2312', 'GBK','UTF-8'));
        $req_str = iconv($encoding,"GB2312",$req_str);
//        $req_str = mb_convert_encoding($req_str, 'GB2312', $encoding);
        $ret = $this->request_by_curl($uri,$req_str);
        $endtime=microtime(true);
        $alltime=$endtime-$startime;
        $this->log("天安投保申请报文：".$req_str);
        $this->log("天安投保返回报文：".$ret);
        $this->log("天安投保反应时间（秒）：".$alltime);
        $result = json_decode($ret);

        $import = new RenXcImportinfo();
        $import->in_company = $productObj->in_company;
        $import->approvaltrans_id = $id;
        $import->cWaterNo = $data['waterNo'];
        $import->cooperation = $data['cooperation'];

        $return = array(
            'waterNo' => $data['waterNo'],
            'retCode' => '',
            'retDesc' => '',
            'policyNum' => '',
            'transTime' => '',
            'epolicyAddress' => '',
        );
        if( $result ) {
            if ($result->retCode == "00") {
                $import->policyNum = $result->policyNo;
                $import->retCode = "00";
                $import->retDesc = $result->returnMsg;
                $import->startDate = $result->startDate;
                $import->endDate = $result->endDate;
                $import->policyStatus = $result->returnMsg;
                $import->realDate = strtotime($result->transTime)?strtotime($result->transTime):time();
                $import->strLockKey = $data['StrLockKey'];
                $import->orderNo = $data['orderNo'];
                $import->epolicyAddress = $result->epolicyAddress;
                $return['retCode'] = $result->retCode;
                $return['retDesc'] = $result->returnMsg;
                $return['policyNum'] = $result->policyNo;
                $return['transTime'] = $result->transTime?$result->transTime:date('Y-m-d H:i:s');
                $return['epolicyAddress'] = $result->epolicyAddress;

                //新增分保记录
                $productObj->insure_number += 1;
                $productObj->save(false);

            } else {
                $import->retCode = "11";
                $import->retDesc = $result->returnMsg;
                $import->startDate = $data['StartDate'];
                $import->endDate = $data['EndDate'];
                $import->policyStatus = "失败";
                $import->realDate = time();
                $import->strLockKey = $data['StrLockKey'];
                $import->orderNo = $data['OrderNo'];
                $return['retCode'] = "11";
                $return['retDesc'] = $result->returnMsg;
            }
        }else{
            $import->retCode = "11";
            $import->retDesc = '核心接口连接失败，请联系管理员';
            $import->policyStatus = "失败";
            $import->realDate = time();
            $return['retCode'] = "11";
            $return['retDesc'] = '核心接口连接失败，请联系管理员';
        }

        $import->createTime = time();
        $import->save(false);
        echo $return_msg = $this->JSON($return);
        $this->log("同程承保返回报文：".$return_msg);
    }

    /*
    * 投保人保
    */
    public function RB($id,$data,$productObj) {
        $uri =  Yii::app()->params['Renbao_toubao'];
        $req_str = $this->commonXml($id,$data,$productObj);
        $startime=microtime(true);
        $encoding = mb_detect_encoding($req_str, array('ASCII','GB2312', 'GBK','UTF-8'));
        $req_str = iconv($encoding,"GB2312",$req_str);
//        $req_str = mb_convert_encoding($req_str, 'GB2312', $encoding);
        $ret = $this->request_by_curl($uri,$req_str);
        $endtime=microtime(true);
        $alltime=$endtime-$startime;
        $this->log("人保投保申请报文：".$req_str);
        $this->log("人保投保返回报文：".$ret);
        $this->log("人保投保反应时间（秒）：".$alltime);
        $result = json_decode($ret);

        $import = new RenXcImportinfo();
        $import->in_company = $productObj->in_company;
        $import->approvaltrans_id = $id;
        $import->cWaterNo = $data['waterNo'];
        $import->cooperation = $data['cooperation'];

        $return = array(
            'waterNo' => $data['waterNo'],
            'retCode' => '',
            'retDesc' => '',
            'policyNum' => '',
            'transTime' => '',
            'epolicyAddress' => '',
        );
        if( $result ) {
            if ($result->retCode == "00") {
                $import->policyNum = $result->policyNo;
                $import->retCode = "00";
                $import->retDesc = $result->returnMsg;
                $import->startDate = $result->startDate;
                $import->endDate = $result->endDate;
                $import->policyStatus = $result->returnMsg;
                $import->realDate = strtotime($result->transTime)?strtotime($result->transTime):time();
                $import->strLockKey = $data['StrLockKey'];
                $import->orderNo = $data['orderNo'];
                $import->epolicyAddress = $result->epolicyAddress;
                $return['retCode'] = $result->retCode;
                $return['retDesc'] = $result->returnMsg;
                $return['policyNum'] = $result->policyNo;
                $return['transTime'] = $result->transTime?$result->transTime:date('Y-m-d H:i:s');
                $return['epolicyAddress'] = $result->epolicyAddress;

                //新增分保记录
                $productObj->insure_number += 1;
                $productObj->save(false);

            } else {
                $import->retCode = "11";
                $import->retDesc = $result->returnMsg;
                $import->startDate = $data['StartDate'];
                $import->endDate = $data['EndDate'];
                $import->policyStatus = "失败";
                $import->realDate = time();
                $import->strLockKey = $data['StrLockKey'];
                $import->orderNo = $data['OrderNo'];
                $return['retCode'] = "11";
                $return['retDesc'] = $result->returnMsg;
            }
        }else{
            $import->retCode = "11";
            $import->retDesc = '核心接口连接失败，请联系管理员';
            $import->policyStatus = "失败";
            $import->realDate = time();
            $return['retCode'] = "11";
            $return['retDesc'] = '核心接口连接失败，请联系管理员';
        }

        $import->createTime = time();
        $import->save(false);
        echo $return_msg = $this->JSON($return);
        $this->log("同程承保返回报文：".$return_msg);
    }

    public function commonXml($id,$data,$productObj) {
        $appData =  RenApprovaltrans::model()->findByPk($id);
        $holderData = CsPolicyholders::model()->findByPk($appData->proposer_id);
        $insuedData = RenInsuredinfo::model()->findAllByAttributes(array("approvaltrans_id"=>$appData->id));
        $i=0;
        $rationType = $productObj->rationType;
        $riskCode = $productObj->riskCode;
        $insuredDataDtoList=array();
        foreach ($insuedData  as $value) {
            $insuredDataDtoList[$i]['insuredName']=$value->InsuedName;
            $insuredDataDtoList[$i]['identifyType']=$value->InsuedZJType;
            $insuredDataDtoList[$i]['identifyNumber']=$value->InsuedZJNo;
            $insuredDataDtoList[$i]['mobile']=$value->InsuedMobile;
            $insuredDataDtoList[$i]['birthday']=$value->birthday;
            $insuredDataDtoList[$i]['sex']=$value->sex;
            $insuredDataDtoList[$i]['insRelationApp']= $value->insRelationApp;
            $i++;
        }
        $data = array(
            "rationType" => $rationType,
            "riskCode" => $riskCode,
            "startDate" => $appData->startDate,
            "endDate" => $appData->endDate,
            "inputDate" => $appData->inputDate,
            "holderNum" => $appData->holderNum,
            "waterNo" => $appData->waterNo,
            "appDataDto" => array(
                "applicantName" => $holderData->ApplicantName,
                "identifyType" => $holderData->ApplicantZJType,
                "identifyNumber" => $holderData->ApplicantZJNum,
                "applicantType" => $holderData->ApplicantType,
                "mobile" => $holderData->ApplicantMobile,
                "sex" => $holderData->sex,
                "birthday" => $holderData->birthday,
            ),
            "insuredDataDtoList" => $insuredDataDtoList,
            "dynamicDto" => array(
                "fieldAA"=>$appData->trip,
                "fieldAB"=>$appData->date?date('Y-m-d', strtotime($appData->date)):"",
                "fieldAC"=>$appData->OrderID,
                "fieldAD"=>$appData->DepartureCity,
                "fieldAE"=>$appData->ArrivalCity,
                "fieldAF"=>$appData->CarNo,
                "fieldAG"=>$appData->CarNum,
                "fieldAH"=>$appData->address?$appData->address:'无法采集',
                "fieldAI"=>$appData->school,
                "fieldAJ"=>$appData->class,
            ),
        );
        if ($productObj->in_company == "TA") { //天安 需增加请求字段
            $nonce = strtoupper(md5(uniqid(mt_rand(), true)));
            $time = time();
            $data['salesCode'] = $productObj->salesCode;
            $data['belongORGCode'] = $productObj->belongORGCode;
            $data['businessMode'] = $productObj->businessMode;
            $data['requestHead'] = array(
                'cooperation' => "tongcheng",
                "nonce" => $nonce,
                "sign" => $this->getSign($nonce, $time),
                "timestamp" => $time,
                "tradeNo" => $time.rand(10000, 99999),
                "tradeDate" => date("Y-m-d H:i:s"),
            );
        }
        $data = json_encode($data);
        return $data;
    }

    //根据产品来分保
    private function getTargetCompany($thirdPartyCode) {
        $products = CsConfig::model()->findAllByAttributes(array("third_party_code"=>$thirdPartyCode));
        if (count($products) > 1) {
            $total_insure_number = 0;
            $proportion = array();
            foreach ($products as $product) {
                //这个产品的所有保司的总承包数量
                $total_insure_number += $product->insure_number;
                $proportion[$product->in_company]['base_proportion'] = floatval($product->proportion);
            }
            foreach ($products as $product) {
                $proportion[$product->in_company]['current_proportion'] = $product->insure_number/$total_insure_number * 100;
                if ($proportion[$product->in_company]['current_proportion'] >= $proportion[$product->in_company]['base_proportion']) {
                    $more_half[$product->in_company] = $proportion[$product->in_company]['base_proportion'] - $proportion[$product->in_company]['current_proportion'];
                } else {
                    $less_half[$product->in_company] = $product->proportion;
                }
            }
            //如果less_half 有值得话,优先
            if ($less_half) {
                $rand = array();
                $max = 0;
                foreach ($less_half as $key=>$value) {
                    if (intval($value) > $max) {
                        $max += intval($value);
                    }
                    for ($i=0;$i<intval($value);$i++) {
                        $rand[] = $key;
                    }
                }
                shuffle($rand);
                $num = rand(0,($max-1));
                $in_company = $rand[$num];
            } else {
                arsort($more_half,SORT_NUMERIC);
                $in_company = key($more_half);
            }
        }
        if (count($products) == 1) {
            $in_company = $products[0]->in_company;
        }
        $product = CsConfig::model()->findByAttributes(array("third_party_code"=>$thirdPartyCode,'in_company'=>$in_company));
        return $product;
    }


    public function request_by_curl($remote_server,$post_string,$ssl=false){
        if(function_exists('curl_init')){
            $ch = curl_init();
            $header[] = "Content-type: text/xml";//定义content-type为xml
            curl_setopt($ch,CURLOPT_URL,$remote_server);
//             curl_setopt($ch, CURLOPT_TIMEOUT, 5);
            curl_setopt($ch,CURLOPT_POST, 1);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$post_string);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            if($ssl){
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            }
            $data = curl_exec($ch);
            curl_close($ch);
            return $data;
        }else{
            return '请先安装curl';
        }
    }

    function getSign($nonce,$time){
        $token =  Yii::app()->params['Tianan_Huo_token'];
        $data = array($token, $nonce, $time);
        sort($data, SORT_STRING);
        $sign_orign = implode('',$data);
        return $sign_haxi = sha1($sign_orign);
    }
    //判断是否为身份证
    function idcard($card) {
        $card = $this->to18Card($card);
        if (strlen($card) != 18) {
            return false;
        }
        $cardBase = substr($card, 0, 17);
        return ($this->getVerifyNum($cardBase) == strtoupper(substr($card, 17, 1)));
    }
    //格式化15位身份证号码为18位
    function to18Card($card) {
        $card = trim($card);
        if (strlen($card) == 18) {
            return $card;
        }
        if (strlen($card) != 15) {
            return false;
        }
        // 如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特殊编码
        if (array_search(substr($card, 12, 3), array('996', '997', '998', '999')) !== false) {
            $card = substr($card, 0, 6).'18'.substr($card, 6, 9);
        } else {
            $card = substr($card, 0, 6).'19'.substr($card, 6, 9);
        }
        $card = $card.$this->getVerifyNum($card);
        return $card;
    }
    // 计算身份证校验码，根据国家标准gb 11643-1999
    function getVerifyNum($cardBase) {
        if (strlen($cardBase) != 17) {
            return false;
        }
        // 加权因子
        $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
        // 校验码对应值
        $verify_number_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
        $checksum = 0;
        for ($i = 0; $i < strlen($cardBase); $i++) {
            $checksum += substr($cardBase, $i, 1) * $factor[$i];
        }
        $mod = $checksum % 11;
        $verify_number = $verify_number_list[$mod];
        return $verify_number;
    }

    //生日和性别提取
    function sexIDCard($IDCard) {
        if (strlen($IDCard) == 18) {
            return $this->check18sex($IDCard);
        } elseif ((strlen($IDCard) == 15)) {
            return $this->check15sex($IDCard);
        } else {
            return false;
        }
    }
    function check18sex($IDCard) {
        $num = intval(substr($IDCard,16,1));
        if(($num%2) == 0) {
            return "02";
        } else {
            return "01";
        }
    }
    function check15sex($IDCard) {
        $num = intval(substr($IDCard,14,1));
        if(($num%2) == 0) {
            return "02";
        } else {
            return "01";
        }
    }

    function birthIDCard($IDCard) {
        if (strlen($IDCard) == 18) {
            return $this->check18birthday($IDCard);
        } elseif ((strlen($IDCard) == 15)) {
            $IDCard = $this->convertIDCard15to18($IDCard);
            return $this->check18birthday($IDCard);
        } else {
            return false;
        }
    }

    function check18birthday($IDCard) {
        $tyear= substr($IDCard,6,4);
        $tmonth= substr($IDCard,10,2);
        $tday= substr($IDCard,12,2);
        return $tyear."-".$tmonth."-".$tday;
    }

    function convertIDCard15to18($IDCard) {
        if (strlen($IDCard) != 15) {
            return false;
        } else {
            // 如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特殊编码
            if (array_search(substr($IDCard, 12, 3), array('996', '997', '998', '999')) !== false) {
                $IDCard = substr($IDCard, 0, 6) . '18' . substr($IDCard, 6, 9);
            } else {
                $IDCard = substr($IDCard, 0, 6) . '19' . substr($IDCard, 6, 9);
            }
        }
        $IDCard = $IDCard . $this->calcIDCardCode($IDCard);
        return $IDCard;
    }
    // 解决json中文乱码
    function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
    {
        static $recursive_counter = 0;
        if (++$recursive_counter > 1000) {
            die('possible deep recursion attack');
        }
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                arrayRecursive($array[$key], $function, $apply_to_keys_also);
            } else {
                $array[$key] = $function($value);
            }

            if ($apply_to_keys_also && is_string($key)) {
                $new_key = $function($key);
                if ($new_key != $key) {
                    $array[$new_key] = $array[$key];
                    unset($array[$key]);
                }
            }
        }
        $recursive_counter--;
    }
    function JSON($array) {
        $this-> arrayRecursive($array, 'urlencode', true);
        $json = json_encode($array);
        return urldecode($json);
    }

    //日志
    private function log($content) {
        $path = "log/".date("Y-m-d");
        if (!file_exists($path)) {
            mkdir($path);
        }
        $path .= "/huoche.log";
        $open=fopen($path,"a");
        fwrite($open,date('Y-m-d H:i:s').':'.$content."\r\n");
        fclose($open);
    }
}